var EventEmitter = function(){
	this._events = {};
	this._maxListeners = 10;
};

EventEmitter.prototype.listeners = function(event){
	var ll = this._events[event];
	if(ll == undefined)
	{
		ll = [];
		this._events[event] = ll;
	}
	return ll;
};

EventEmitter.prototype.addListener = function(event, listener){
	var ll = this.listeners(event);
	
	ll.push({func:listener, cnt:-1});
	if(ll.length > this._maxListeners){
		console.warn("Warning: " + ll.length + " events <" + event  + "> in eventListeners, shoud be <=" + this._maxListeners);
	}
};

EventEmitter.prototype.on = function(event, listener){
	var ll = this.listeners(event);
	ll.push({func:listener, cnt:-1});
	console.log("add listener for " + event);

	return this;
};

EventEmitter.prototype.once = function(event, listener){
	var ll = this.listeners(event);
	ll.push({func:listener, cnt:1});
};

EventEmitter.prototype.removeListener = function(event, listener){
	if(!this._events[event])
		return;

	var ll = this.getListener(event);
	for(var i=0; i<ll; i++)
	{
		if(ll[i].listener == listener){
			ll.splice(i, 1);
			break;
		}
	}

	if(ll.length == 0){
		delete this._events[event];
	}
	
};

EventEmitter.prototype.removeAllListeners = function(event){
	if(this._events[event])
		delete this._events[event];
};

EventEmitter.prototype.setMaxListeners = function(n){
	this._maxListeners = n;
};

EventEmitter.prototype.emit =  function(event, arg1, arg2, arg3, arg4, arg5){
	if(!this._events[event])
	{
		// console.log("not found event-" + event);
		return false;
	}

	var ll = this._events[event];
	for(var i=0; i<ll.length; i++)
	{
		if(ll[i].cnt != 0){
			ll[i].func(arg1, arg2, arg3, arg4, arg5);
			if(ll[i].cnt == 1)
			{
				ll[i].cnt = 0;
			}
		}
	}	
	return true;
};


module.exports = {EventEmitter: EventEmitter};

// var eventEmitter = new EventEmitter();

/*  for testing only
var dog = function(name){
	this.name = name;
	console.log("create dog: " + this.name);
	this.bark = function(){
		console.log("Hi-" + this.name + " barking..");
		emitter.emit('bark', this, "hello from" + this.name);
	}
};



emitter.on('bark', function(d, info){
	console.log("dog - " + d.name + " is barking:" + info);
});

emitter.once('bark', function(d){
	console.log("小狗-" + d.name + "在叫了");
});

var a = new dog('金毛');
var b = new dog('边境');


a.bark();
b.bark();
a.bark();

*/
